package com.base.core.flex;

import java.rmi.server.RemoteObject;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import flex.messaging.MessageDestination;
import flex.messaging.config.ConfigMap;
import flex.messaging.services.AbstractBootstrapService;
import flex.messaging.services.Service;
import flex.messaging.services.remoting.RemotingDestination;

/**
 * 动态生成BEAN的类，于服务器启动时执行，在services-config.xml文件中配置
 * @author Ken
 *
 */
public class SpringRemotingDestinationBootstrapService extends
		AbstractBootstrapService {
	
	private static Logger logger = LoggerFactory
			.getLogger(SpringRemotingDestinationBootstrapService.class);
	
	@Override
	public void initialize(String arg0, ConfigMap arg1) {
		// TODO Auto-generated method stub
		String serviceId = arg1.getPropertyAsString("service-id", "remoting-service");
		Service roService = broker.getService(serviceId);
		if (roService == null)
			System.out.println("not found Service with serviceId:" + serviceId);
		//创建BEAN
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(broker.getServletContext());
		List<String> addedBeanNames = new ArrayList<String>();
		for (String beanName : wac.getBeanDefinitionNames()) {
			Class type = wac.getType(beanName);
			boolean isCreateSpringDestination = !type
					.isAnnotationPresent(RemoteObject.class)
					|| isCreateDestination(beanName, type);

			if (isCreateSpringDestination) {
				RemotingDestination destination = (RemotingDestination) roService
						.createDestination(beanName);

				destination.setSource(beanName);
				String str = arg1.getPropertyAsString("dest-factory", "spring");
				destination.setFactory(str);

				str = arg1.getProperty("dest-adapter");
				if (str != null) {
					destination.createAdapter(str);
				}
				
				str = arg1.getProperty("dest-scope");
				if (str != null) {
					destination.setScope(str);
				}
				
				str = arg1.getProperty("dest-security-constraint");
				if (str != null) {
					destination.setSecurityConstraint(str);
				}
				
				str = arg1.getPropertyAsString("dest-channel", "my-amf");
				if (str != null) {
					destination.addChannel(str);
				}

				roService.addDestination(destination);
				//添加到bean列表
				addedBeanNames.add(beanName);
			}
		}
	}
	
	protected boolean isCreateDestination(String beanName, Class type) {
		return false;
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub

	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}

}
